#include "bsp_motor_driver.h"

// 8�ಽ�����У��ɸ���ʵ�ʵ��������
static const uint8_t step_table[8][4] = {
    {0,1,1,1},
    {0,0,1,1},
    {1,0,1,1},
    {1,0,0,1},
    {1,1,0,1},
    {1,1,0,0},
    {1,1,1,0},
    {0,1,1,0}
};

/**
 * @brief �����ʼ��
 * @param motor  ���ʵ��ָ��
 * @param pinmap ����ӳ��
 */
void Motor_Init(MotorHandle_t* motor, MotorPinMap_t pinmap)
{
    motor->pinmap = pinmap;
    motor->phase = 0;
    motor->last_tick = 0;
    motor->step_count = 0;
    motor->target_step = 0;
}

/**
 * @brief ����һ��
 * @param motor ���ʵ��ָ��
 * @param dir   ����
 * @param cycle ��������(ms)
 */
void Motor_Step(MotorHandle_t* motor, MOTOR_DIR dir, uint32_t cycle)
{
    uint32_t now = HAL_GetTick();
    if(now - motor->last_tick < cycle) return;

    // ��������ź�
    for(int i=0; i<4; i++) {
        HAL_GPIO_WritePin(motor->pinmap.port[i], motor->pinmap.pin[i], 
            step_table[motor->phase][i] ? GPIO_PIN_SET : GPIO_PIN_RESET);
    }

    // ��λ����
    if(dir == MOTOR_FORWARD)
        motor->phase = (motor->phase + 1) % 8;
    else
        motor->phase = (motor->phase + 7) % 8; // ��ת

    motor->last_tick = now;
    motor->step_count++;
}

/**
 * @brief ���Ƕ�����
 * @param motor ���ʵ��ָ��
 * @param dir   ����
 * @param cycle ��������(ms)
 * @param angle Ŀ��Ƕ�
 */
void Motor_RunToAngle(MotorHandle_t* motor, MOTOR_DIR dir, uint32_t cycle, uint16_t angle)
{
    // ��64��/45��Ϊ��
    motor->target_step = (uint16_t)((64.0 * angle / 45.0) * 8);
    if(motor->step_count < motor->target_step) {
        Motor_Step(motor, dir, cycle);
    }
}
